define(function(require, exports, module) {
    "use strict";
    var $ = require("$"),
        app = require("dist/application/app"),
        config = app.config;
    var tips = require("dist/tips/init")
    var data = require("./data");
    var box_tmp = require("./template/area_box.html");
    var cities_tmp = require("./template/area_cities.html");
    var RegionPicker = function(element,name,text) {
        this.currProvince = "110000";
        this.element = element;
        this.name = name;
        this.text=text;
        this.selectedMap = {};
        if (this.element) {
            var attr = $('input[type="hidden"]', this.element).val();
            if (attr) {
                this.selectedMap = window.JSON.parse(attr)
            };
        }
        this.selectCities = {};
        this.selectProvinceyInit();
        this.init();

    }
    RegionPicker.prototype.init = function() {
        this.data = data;
        var _self = this;
        $(document).on("change", "select.js_province", function() {
            _self.currProvince = $(this).val();
            _self.changeCities()
        })
        $(document).on("click", "input.js_checkall", function(e) {
            var $this = $(e.target),
                checked = $this.is(':checked'),
                val = $this.val();
            var checkitems = $("input.js_checkitem", _self.citiesEl());
            checkitems.prop('checked', checked);
            checkitems.trigger("select")
            _self.checkAll(checked);

        })
        $(document).on("click", "input.js_checkitem", function(e) {
            e && e.stopPropagation();
            _self.selectCity(this);
        })
        $(document).bind("select", "input.js_checkitem", function(e) {
            e && e.stopPropagation();
            _self.selectCity(e.target);
        });
    };
    RegionPicker.prototype.showSelectedCitiesInit = function() {
        var parr = new Array();
        for (var pid in this.selectedMap) {
            var p = this.selectedMap[pid];
            var pd = this.data[pid];
            if (p["checkall"] && p["checkall"] == true) {
                parr.push(pd.name);
            } else {
                var carr = new Array();
                for (var c in p) {
                    var item = p[c];
                    if (item instanceof Object) {
                        carr.push(p[c].name);
                    }
                }
                if (carr.length > 0) {
                    parr.push("{0} [{1}] ".format(pd.name, carr.join("、")))
                };
            }
        }
        return parr.join("、");
    };
    RegionPicker.prototype.showSelectedCities = function() {
        var $selected_cities = $("p.js_selected_cities");
        var selectedHtml = this.showSelectedCitiesInit();
        $selected_cities.html(selectedHtml.length > 1 ? "已选：" + selectedHtml : config.empty)

    };
    RegionPicker.prototype.html = function() {
        var render = template.compile(box_tmp);
        return render({
            provinces: this.data,
            cities_html: this.citiesHtml()
        });
    };
    RegionPicker.prototype.selectCity = function(target) {
        var $this = $(target),
            city = $this.data();
        var checked = $this.prop('checked');
        var p = this.selectedMap[this.currProvince];
        if (checked) {
            var selectCities = this.selectCities;
            p[city.id] = selectCities[city.id];
            if (this.checkCityEl().length == Object.keys(selectCities).length) {
                this.checkAll(true);
            };
        } else {
            this.checkAll(false);
            delete this.selectedMap[this.currProvince][city.id];
        }
        this.showSelectedCities();
    };
    RegionPicker.prototype.selectProvinceyInit = function() {
        if (!this.selectedMap[this.currProvince]) {
            this.selectedMap[this.currProvince] = {};
            this.selectedMap[this.currProvince]["checkall"] = false;
        };
    };

    RegionPicker.prototype.success = function() {
        var showHtml = this.showSelectedCitiesInit();
        var msg=this.element.data("msg") || "未指定地区",classes=this.element.data("classes") || "";
        this.element.html(showHtml.length > 1 ? showHtml : "<span class='js_no_area "+classes+"'>"+msg+" </span>");
        this.element.append("<input type='hidden' name='{0}'  value='{1}'>".format(this.name, window.JSON.stringify(this.selectedMap)));
        this.element.append("<input type='hidden' name='{0}'  value='{1}'>".format(this.text,showHtml))
    };
    RegionPicker.prototype.checkAll = function(checked) {
        this.checkAllEl().prop('checked', checked);
        this.selectedMap[this.currProvince]["checkall"] = checked;

    };
    RegionPicker.prototype.checkAllEl = function() {
        return $("input.js_checkall", this.citiesEl());
    };
    RegionPicker.prototype.checkCityEl = function() {
        return $("input.js_checkitem:checked", this.citiesEl());
    };
    RegionPicker.prototype.citiesEl = function() {
        return $("ul.js_cities");
    };
    RegionPicker.prototype.changeCities = function() {
        this.selectProvinceyInit();
        this.citiesEl().html(this.citiesHtml())
    };
    RegionPicker.prototype.checkSelectedCity = function(city) {
        var p = this.selectedMap[this.currProvince];
        if (p["checkall"] && p["checkall"] == true) {
            return true;
        } else {
            return p[city] != undefined;
        }
    },
    RegionPicker.prototype.citiesHtml = function() {
        this.selectCities = this.data[this.currProvince].cities;
        var data = this.selectCities;
        var render = template.compile(cities_tmp);
        var count = Object.keys(this.selectCities).length;
        for (var c in data) {
            data[c]["checked"] = (this.checkSelectedCity(c) ? 'checked="checked"' : '')
        }
        return render({
            data: data,
            checkAllShow: count > 1,
            checkAll: this.selectedMap[this.currProvince]["checkall"] ? 'checked="checked"' : '',
            currProvince: this.currProvince
        });
    };
    $(document).on("click", ".js_edit_area", function() {
        var $this = $(this),
            $area_item = $this.nextAll("span.js_area_item");
        var Region_Picker = new RegionPicker($area_item, $this.data("name"),$this.data("text"));
        var dialog = tips.msgbox.dialog({
            message: Region_Picker.html(),
            title: "选择地区",
            buttons: {
                success: {
                    label: "确定",
                    className: "btn-primary",
                    callback: function() {
                        Region_Picker.success()
                    }
                },
                cancel: {
                    label: "取消"
                }
            }
        });
        dialog.on("shown.bs.modal", function() {
             Region_Picker.showSelectedCities();
        }); 
    });
    $(document).on("click",'button[type="submit"]',function  () {
        var $no_area=$(".js_no_area"),flag=true;
        $no_area.each(function(){
            if (!$(this).hasClass('no_validate')) {
                flag=false;
            };
        });
        if(!flag){
           config.msg.info($(".js_edit_area").data("msg") ||"请选择指定地区"); 
       }
        return flag;
    })
})
